﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ProjectStatic.Models;
using ProjectStatic.Services;
using System.Collections.Generic;
using System.Web.Http;

namespace ProjectStatic.Controllers
{
    public class FavorProjectController : ApiController
    {
        // GET api/favorproject
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/favorproject/5
        public string Get(string name)
        {
            string sql = string.Format("select * from projects,FavorProject" +
                " where FavorProject.Name='{0}' and FavorProject.FavorPrjId=projects.项目编号", name);
            DatasDb<Project> dbs = new DatasDb<Project>();
            List<Project> prjs = dbs.QueryDatas(sql);
            return JsonConvert.SerializeObject(prjs);
        }

        // POST api/favorproject
        public void Post([FromBody]string value)
        {
            JObject jsonData = JObject.Parse(value);
            string name = jsonData["name"].ToString();
            string[] prjList = jsonData["prjList"].ToObject<string[]>();
            List<string> sqlList = new List<string>();
            foreach (string str in prjList)
            {
                string sql = string.Format("delete from FavorProject where Name='{0}' and FavorPrjId ='{1}'", name, str);
                sqlList.Add(sql);
            }
            DbHelperSQL.ExecuteSqlTran(sqlList);
 
        }

        // PUT api/favorproject
        public bool Put([FromBody]string value)
        {
            //JObject jsonData = JObject.Parse(value);
            //string prjId = jsonData["prjId"].ToString();
            //string name = jsonData["name"].ToString();
            JObject jsonData = JObject.Parse(value);
            string name = jsonData["name"].ToString();
            string[] prjList = jsonData["prjList"].ToObject<string[]>();
            List<string> sqlList = new List<string>();
            foreach (string str in prjList)
            {
                FavorProject prj = new FavorProject()
                {
                    FavorPrjId = str,
                    Name = name
                };
                string sql = string.Format("delete from FavorProject where Name='{0}' and FavorPrjId ='{1}'", name, str);
                sqlList.Add(sql);
                sql = prj.GenerateInsertSqlStr();
                sqlList.Add(sql);
            }

            DbHelperSQL.ExecuteSqlTran(sqlList);
            return true;
        }

        // DELETE api/favorproject/5
        public string Delete(string name, string prjId)
        {
            string sql = string.Format("delete from FavorProject where Name='{0}' and FavorPrjId ='{1}'"
                , name, prjId);
            DbHelperSQL.ExecuteSql(sql);
            return name + " " + prjId;
        }
    }
}
